﻿using analy;
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Script.Serialization;

namespace Communicate
{
    /// <summary>
    /// 发送协议使用串口通过GPRS模块发送
    /// </summary>
   public  class AgreePrivateBySerialPort2GPRS:AgreePrivateBySerialPort  
    {
        public AgreePrivateBySerialPort2GPRS(ReturnRes RE)
        {
            AgreePrivateBySerialPortInit(RE,1);
        }

      internal   override  void SP_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {          
            List<byte> ReceiveData = new List<byte>();
            while (true)
            {
                try
                {
                    ReceiveData.Add((byte)SP.ReadByte());
                }
                catch (Exception)
                {
                    break;
                }
            }
            List<byte[]> bytes = new List<byte[]>();
            bytes = GetJson(ReceiveData.ToArray()); //json粘包处理
            foreach (var item in bytes)
            {
                try
                {
                    JavaScriptSerializer js = new JavaScriptSerializer();
                    string recstring = System.Text.Encoding.Default.GetString(item);
                    Dictionary<string, object> listres = js.Deserialize<Dictionary<string, object>>(recstring);
                    if (listres.Keys.Contains("device_type") && listres.Keys.Contains("device_cmd") && listres.Keys.Contains("device_code") && listres.Keys.Contains("gprs_code"))
                    {
                        if (Convert.ToInt32(listres["device_type"]) == 10 && Convert.ToInt32(listres["device_cmd"]) == 1)
                        {
                            AP.locks = 1;  //打包数据发送成功
                            AP.clearstatue(AP.TaskPackage[0].ToArray());
                            AP.TaskPackage.RemoveAt(0);
                        }
                        if (Convert.ToInt32(listres["device_type"]) == 10 && Convert.ToInt32(listres["device_cmd"]) == 6)
                            respondServer(listres);  //全部操作成功
                        if (Convert.ToInt32(listres["device_type"]) == 10 && Convert.ToInt32(listres["device_cmd"]) == 2)
                            respondServer(listres); //失败数据打包
                    }
                    RR(new Communicate.AgreePrivateBySerialPort.ReceiveStruct() {  AnalyResult=recstring, ReceiveData=item });
                }
                catch (Exception )
                {
                    //json反序列化失败就什么也不做

                }

            }
           
        }

        /// <summary>
        /// 收到byte[]中，把{}中的数据变成list<byte[]>中一项
        /// </summary>
        /// <param name="reg">收到的数组</param>
        /// <returns></returns>
        private List<byte[]> GetJson(byte[] reg)
        {
            List<byte[]> ReadJson = new List<byte[]>();
            ReadJson = JsonSpliter.Spliter.IsJsons(reg);
            return ReadJson;
        }

        private void respondServer(Dictionary<string, object> D)
        {
            string GPRSCode = D["gprs_code"].ToString() ;
            byte types = Convert.ToByte(D["device_type"]);
            byte oper = Convert.ToByte(D["device_cmd"]);
            int[] ids = new int[] { Convert.ToInt32(D["device_code"].ToString().Substring(2, D["device_code"].ToString().Length - 2)) };
            AP.sendImmediatelyTask(GPRSCode, types, oper, ids, null);
        }

    }
}
